package cn.tom.controller.adm;

import cn.tom.entity.Book;
import cn.tom.service.BookService;
import cn.tom.service.BookTypeService;
import cn.tom.service.LargeFileService;
import cn.tom.tool.XJson;
import cn.tom.tool.XResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping({"/api/adm/book"})
@RestController

public class BookController {
    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private BookService bookService;
    @Autowired
    private LargeFileService largeFileService;

    @GetMapping({"/findById/{bookid}"})
    public XJson findById(@PathVariable Integer bookid) {
        return XResp.pack(200, "", this.bookService.findOne(bookid));
    }

    @GetMapping({"/del/{bookid}"})
    public XJson remove(@PathVariable Integer bookid) {
        int ret = this.bookService.remove(bookid);
        if (ret==1) {
            return XResp.pack(200, "删除成功", "");
        }
        return XResp.pack(200, "删除失败", "");
    }

    @GetMapping({"/findByPage/{start}/{num}"})
    public XJson findBookPages(@PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        Map<String, Object> map = new HashMap<>();
        map.put("books", this.bookService.findPageType((start - 1) * num, num, null));
        map.put("total", this.bookService.getCountType(null));
        return XResp.pack(200, "", map);
    }

    @PostMapping({"/add"})
    public XJson add(@RequestParam(value = "mypic", required = false) MultipartFile file, Book b) throws IOException {
        this.log.info("===========b.getTmake" + b.getTmake());
        Map<String, Object> map = new HashMap<>();
        this.log.info("file=" + file);
        this.log.info(b.toString());
        String fileName = "";
        String msg = "操作失败 .....";
        if (file != null) {
            fileName = file.getOriginalFilename();
        }
        System.out.println(fileName);
        if (b.getId() == null || b.getId() == 0) {
            if (file != null && file.getSize() > 0) {
                System.out.println("如果有更新图片， 需要删除旧的图片， 而后添加新的图片");
                String uuid = UUID.randomUUID().toString().replace("-", "");
                b.setPic(uuid);
                this.largeFileService.add(uuid, fileName, file.getBytes());
            }
            this.bookService.add(b);
            System.out.println("新的的书id=" + b.getId());
            msg = "添加本书成功...";
        }
        if (b.getId() != null && b.getId() > 0) {
            if (file != null && file.getSize() > 0) {
                System.out.println("删除旧的图片");
                this.largeFileService.delete(b.getPic());
                String uuid2 = UUID.randomUUID().toString().replace("-", "");
                b.setPic(uuid2);
                this.largeFileService.add(uuid2, fileName, file.getBytes());
            }
            System.out.println("修改的书id=" + b.getId());
            msg = "更新成功...";
            this.bookService.update(b);
        }
        map.put("book", this.bookService.findOne(b.getId().intValue()));
        return XResp.pack(200, msg, map);
    }

    @GetMapping({"/show/{id}"})
    public void dispaly(@PathVariable String id, HttpServletResponse response) {
        if (id != null) {
            byte[] buf = (byte[]) this.largeFileService.findOne(id).getContent();
            try {
                response.setContentType("image/jpeg");
                response.getOutputStream().write(buf);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder webdataBinder) {
        webdataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String text) throws IllegalArgumentException {
                if (text.indexOf("-") > 0) {
                    if (text.indexOf(" ") < 1) {
                        text = text + " 00:00:00";
                    }
                    try {
                        setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(text));
                    } catch (Exception e) {
                        System.out.println("书本日期错误...." + text);
                        setValue(new Date());
                    }
                } else {
                    setValue(new Date(Long.valueOf(text)));
                }
            }
        });
    }
}
